import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { ChatManager } from '@/services/ChatManager'
import { message } from '@/services/message'
import { ApiResponse, Conversation } from '@/types/api'
export interface ChatMessage {
  id: string
  role: 'user' | 'assistant'
  content: string
  timestamp: number
}

export interface ChatSession {
  id: string
  title: string
  messages: ChatMessage[]
  createdAt: number
  updatedAt: number
}

export const useChatStore = defineStore('chat', () => {
  const sessions = ref<ChatSession[]>([])
  const currentSessionId = ref<string | null>(null)
  const isLoading = ref(false)
  const chatManager = new ChatManager()

  const currentSession = computed(() => 
    sessions.value.find(s => s.id === currentSessionId.value)
  )

  const createSession = () => {
    const newSession: ChatSession = {
      id: Date.now().toString(),
      title: '新对话',
      messages: [],
      createdAt: Date.now(),
      updatedAt: Date.now()
    }
    sessions.value.unshift(newSession)
    currentSessionId.value = newSession.id
    return newSession
  }

  const initialize = async () => {
    console.log('Initializing chat service...')
    try {
      await chatManager.initialize({
        onMessage: (content) => {
          console.log('Chat store received message:', content)
          const session = currentSession.value
          if (session && session.messages.length > 0) {
            const lastMessage = session.messages[session.messages.length - 1]
            if (lastMessage.role === 'assistant') {
              // 保留原始格式，不对内容进行trim处理
              // 直接拼接内容，保留所有空格和换行符
              lastMessage.content += content
            } else {
              // 如果最后一条消息不是AI，则创建新的AI消息
              console.log('Creating new assistant message')
              const aiMessage = {
                id: Date.now().toString(),
                role: 'assistant' as const,
                content: content, // 保留原始格式，不进行trim
                timestamp: Date.now()
              }
              session.messages.push(aiMessage)
            }
          } else if (session) {
            // 如果会话存在但没有消息，创建第一条AI消息
            console.log('Creating first assistant message in session')
            const aiMessage = {
              id: Date.now().toString(),
              role: 'assistant' as const,
              content: content, // 保留原始格式，不进行trim
              timestamp: Date.now()
            }
            session.messages.push(aiMessage)
          }
        },
        onError: (error) => {
          console.error('Chat error:', error)
          message.error(error)
        }
      })
      console.log('Chat service initialized')
    } catch (error) {
      console.error('Failed to initialize chat service:', error)
      message.error('聊天服务初始化失败，请刷新页面重试')
    }
  }

  const sendMessage = async (content: string, onChunk?: (chunk: string) => void) => {
    if (!currentSessionId.value) {
      createSession()
    }

    const session = currentSession.value
    if (!session) return

    const userMessage = {
      id: Date.now().toString(),
      role: 'user' as const,
      content,
      timestamp: Date.now()
    }

    try {
      // 先添加用户消息
      session.messages.push(userMessage)
      session.updatedAt = Date.now()
      
      // 设置isLoading状态
      isLoading.value = true

      // 发送消息
      const response = await chatManager.sendMessage(
        content,
        session.id ? parseInt(session.id) : undefined
      )

      // 如果是新会话，更新会话信息
      if (response.conversationId) {
        const newSessionId = response.conversationId.toString()
        const currentMessages = [...session.messages]
        
        // 重新加载会话列表
        await loadSessions()
        
        // 更新当前会话
        currentSessionId.value = newSessionId
        const updatedSession = sessions.value.find(s => s.id === newSessionId)
        if (updatedSession) {
          updatedSession.messages = currentMessages
        }
      }

    } catch (error) {
      console.error('Failed to send message:', error)
      session.messages.pop()
      throw error
    } finally {
      // 重置isLoading状态
      isLoading.value = false
    }
  }

  const loadHistory = async (sessionId: string) => {
    // 如果是新创建的会话，不加载历史记录
    if (!sessionId || !sessions.value.find(s => s.id === sessionId)) {
      return
    }

    try {
      isLoading.value = true
      const response = await fetch(`/api/chat/conversations/${sessionId}`, {
        headers: {
          'Authorization': `Bearer ${sessionStorage.getItem('token') || localStorage.getItem('token')}`
        }
      })

      const data = await response.json() as ApiResponse<ChatMessage[]>
      
      if (data.code === 200 && data.data) {
        const session = sessions.value.find(s => s.id === sessionId)
        if (session) {
          session.messages = data.data.map(msg => ({
            id: Date.now().toString() + Math.random(),
            role: msg.role,
            content: msg.content,
            timestamp: Date.now()
          }))
        }
      } else {
        throw new Error(data.message)
      }
    } catch (error) {
      console.error('Failed to load history:', error)
      message.error(error instanceof Error ? error.message : '加载历史记录失败')
    } finally {
      isLoading.value = false
    }
  }

  const deleteSession = async (sessionId: string) => {
    try {
      const response = await fetch(`/api/chat/conversations/${sessionId}`, {
        method: 'DELETE',
        headers: {
          'Authorization': `Bearer ${sessionStorage.getItem('token') || localStorage.getItem('token')}`
        }
      })

      const data = await response.json() as ApiResponse<null>

      if (data.code === 200) {
        // 删除成功，从本地状态中移除会话
        const index = sessions.value.findIndex(s => s.id === sessionId)
        if (index > -1) {
          sessions.value.splice(index, 1)
          // 如果删除的是当前会话，切换到第一个会话或清空当前会话
          if (currentSessionId.value === sessionId) {
            currentSessionId.value = sessions.value[0]?.id || null
          }
        }
        message.success('删除成功')
      } else {
        // 处理各种错误情况
        switch (data.message) {
          case '请先登录':
            message.error('登录已过期，请重新登录')
            // 可以在这里触发登出操作
            break
          case '请重新登录':
            message.error('登录已失效，请重新登录')
            // 可以在这里触发登出操作
            break
          case '会话不存在或无权限删除':
            message.error('无法删除该会话')
            // 重新加载会话列表
            await loadSessions()
            break
          default:
            message.error(data.message || '删除失败')
        }
        throw new Error(data.message)
      }
    } catch (error) {
      console.error('Failed to delete session:', error)
      throw error
    }
  }

  const clearSessions = () => {
    sessions.value = []
    currentSessionId.value = null
  }

  const loadSessions = async () => {
    try {
      isLoading.value = true
      const response = await fetch('/api/chat/conversations', {
        headers: {
          'Authorization': `Bearer ${sessionStorage.getItem('token') || localStorage.getItem('token')}`,
          'Content-Type': 'application/json'
        }
      })

      const data = await response.json() as ApiResponse<Conversation[]>
      
      if (data.code === 200 && data.data) {
        sessions.value = data.data.map(conversation => ({
          id: conversation.conversationId.toString(),
          title: conversation.title,
          messages: [],
          createdAt: new Date(conversation.createTime).getTime(),
          updatedAt: new Date(conversation.updateTime).getTime()
        }))
      } else {
        throw new Error(data.message)
      }
    } catch (error) {
      console.error('Failed to load sessions:', error)
      message.error(error instanceof Error ? error.message : '加载会话列表失败')
    } finally {
      isLoading.value = false
    }
  }

  const generateAIResponse = (userMessage: string): string => {
    const responses = [
      `理解您的问题是关于"${userMessage.slice(0, 10)}..."，让我为您解答：\n\n这是一个很好的问题！根据我的理解：\n\n1. 首先...\n2. 其次...\n3. 最后...\n\n希望这个回答对您有帮助！`,
      `关于"${userMessage.slice(0, 10)}..."，这里有一个示例：\n\n\`\`\`javascript\nconst example = "Hello World";\nconsole.log(example);\n\`\`\`\n\n您可以参考这个示例来理解。`,
      `让我用一个比喻来解释"${userMessage.slice(0, 10)}..."：\n\n想象一下...\n\n这样是不是更容理解了？`
    ]
    return responses[Math.floor(Math.random() * responses.length)]
  }

  return {
    sessions,
    currentSessionId,
    currentSession,
    isLoading,
    initialize,
    createSession,
    sendMessage,
    deleteSession,
    clearSessions,
    loadSessions,
    loadHistory
  }
})